import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
import { lStorage } from '@/utils/storage'
import { nextTick } from 'vue'

export interface TabRoute {
  path: string
  name: string
  meta: {
    hidden: boolean
    title: string
    keepAlive: boolean
    icon: string
    hasPerm: string[]
    affix?: boolean
  }
}

// 默认首页路由
const Home: TabRoute = {
  path: '/index',
  name: 'index',
  meta: {
    hidden: false,
    title: '首页',
    keepAlive: true,
    icon: 'dashboard',
    hasPerm: ['viewHome'],
    affix: true,
  },
}

// 静态路由列表，用于排除
const STATIC_ROUTES = ['/login', '/404', '/index'] as const

interface TabsState {
  tabs: TabRoute[]
  activeTab: string
}

export const useTabsStore = defineStore('tabs', {
  state: (): TabsState => ({
    tabs: [Home],
    activeTab: '',
  }),

  getters: {
    // 获取当前激活的标签页
    currentTab: (state) =>
      state.tabs.find((tab) => tab.path === state.activeTab),

    // 获取可关闭的标签页
    closeableTabs: (state) => state.tabs.filter((tab) => !tab.meta.affix),
  },

  actions: {
    // 初始化 Tabs 和当前高亮路由
    initTabs() {
      try {
        const cachedTabs: TabRoute[] = [Home]
        const localTabs = lStorage.get<TabRoute[]>('WXAI_TABS') || []

        const uniqueTabsMap = new Map<string, TabRoute>()
          ;[...cachedTabs, ...localTabs].forEach((tab) => {
            if (this.isValidTab(tab)) {
              uniqueTabsMap.set(tab.path, tab)
            }
          })

        this.tabs = Array.from(uniqueTabsMap.values())
        this.activeTab = lStorage.get<string>('WXAI_ACTIVE_TAB') || '/index'
      } catch (error) {
        console.error('初始化标签页失败:', error)
        this.tabs = [Home]
        this.activeTab = '/index'
      }
    },

    // 验证标签页数据是否有效
    isValidTab(tab: any): tab is TabRoute {
      return (
        tab &&
        typeof tab.path === 'string' &&
        typeof tab.name === 'string' &&
        tab.meta &&
        typeof tab.meta.title === 'string'
      )
    },

    // 添加一个新 Tab
    addTab(route: RouteLocationNormalized & TabRoute) {
      try {
        const routePath = route.path
        if (
          STATIC_ROUTES.includes(routePath as (typeof STATIC_ROUTES)[number]) ||
          !route.meta ||
          Object.keys(route.meta).length === 0
        ) {
          return
        }

        const existingTab = this.tabs.find((tab) => tab.path === routePath)
        if (existingTab) {
          this.setActiveTab(routePath)
          return
        }

        const newTab: TabRoute = {
          path: routePath,
          name: route.name as string,
          meta: {
            hidden: route.meta.hidden ?? false,
            title: route.meta.title as string,
            keepAlive: route.meta.keepAlive ?? false,
            icon: route.meta.icon as string,
            hasPerm: (route.meta.hasPerm as string[]) || [],
          },
        }

        this.tabs.push(newTab)
        this.setActiveTab(routePath)
        lStorage.set('WXAI_TABS', this.tabs)
      } catch (error) {
        console.error('添加标签页失败:', error)
      }
    },

    // 设置当前高亮的 Tab
    setActiveTab(path: string) {
      try {
        this.activeTab = path
        lStorage.set('WXAI_ACTIVE_TAB', path)
      } catch (error) {
        console.error('设置活动标签页失败:', error)
      }
    },

    // 移除一个 Tab
    async removeTab(path: string, router: any) {
      try {
        if (path === Home.path) {
          return
        }

        const currentIndex = this.tabs.findIndex((tab) => tab.path === path)
        if (currentIndex === -1) return

        if (this.activeTab === path) {
          const nextTab =
            this.tabs[currentIndex - 1] || this.tabs[currentIndex + 1]
          if (nextTab) {
            this.setActiveTab(nextTab.path)
            await nextTick()
            await router.push(nextTab.path)
          }
        }

        this.tabs = this.tabs.filter((tab) => tab.path !== path)
        lStorage.set('WXAI_TABS', this.tabs)
      } catch (error) {
        console.error('移除标签页失败:', error)
      }
    },

    // 清除所有标签页
    clearTabs() {
      try {
        this.tabs = [Home]
        lStorage.set('WXAI_TABS', [Home])
        this.activeTab = ''
        lStorage.remove('WXAI_ACTIVE_TAB')
      } catch (error) {
        console.error('清除标签页失败:', error)
      }
    },
  },
})
